package com.example.newdemo05;

import static com.example.newdemo05.MainActivity.assetFilePath;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.newdemo05.classify.ImageNetClasses;

import org.pytorch.IValue;
import org.pytorch.Module;
import org.pytorch.Tensor;
import org.pytorch.torchvision.TensorImageUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class TakePicturesActivity extends AppCompatActivity {
    private TextureView textureView;
    private TextView textPrediction;
    private Button openCam;
    private ImageView v_img;
    Module module = null;
    private CameraDevice cameraDevice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_pictures);
        initView();
    }
    private void initView(){
        v_img = findViewById(R.id.image);
        textPrediction = findViewById(R.id.text_prediction);
        openCam = findViewById(R.id.btn_capture);
        openCam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startCamera();
            }
        });
    }
    // 打开相机
    public void startCamera(){
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        //调用setDataAndType方法，指定了选择的数据类型为图片
        //设置数据的URI为MediaStore.Images.Media.EXTERNAL_CONTENT_URI，表示选择外部存储中的图片
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        //调用startActivityForResult方法，将Intent发送给系统，并指定一个请求码为2，以便在之后的回调中处理用户选择的图片
        startActivityForResult(intent, 2);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            Log.e(this.getClass().getName(), "Result:" + data.toString());
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                v_img.setImageURI(uri);
                ContentResolver cr = getContentResolver();
                InputStream inputStream = null;
                try {
                    inputStream = cr.openInputStream(uri);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                imgClassify(bitmap);
                Log.e(this.getClass().getName(), "Uri:" + String.valueOf(uri));

            }
        }
    }
    private void imgClassify(Bitmap img){
        try {
            // 加载PyTorch序列化模型
            module = Module.load(assetFilePath(this, "model101.pt"));
        } catch (IOException e) {
            Log.e("PytorchHelloWorld", "Error reading assets", e);
            finish();
        }
        v_img.setImageBitmap(img);
        // 建立输入张量
        final Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(img,
                TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB);
        // 运行模型推理
        final Tensor outputTensor = module.forward(IValue.from(inputTensor)).toTensor();
        // 获取推理结果
        final float[] scores = outputTensor.getDataAsFloatArray();
        //  获取概率最高的分类的索引号
        float maxScore = -Float.MAX_VALUE;
        int maxScoreIdx = -1;
        for (int i = 0; i < scores.length; i++) {
            if (scores[i] > maxScore) {
                maxScore = scores[i];
                maxScoreIdx = i;
            }
        }
        //通过索引号获得分类名称
        String className = ImageNetClasses.IMAGENET_CLASSES[maxScoreIdx];
        textPrediction.setText("识别结果为:"+className);
    }


}